package master.quantumComputerIO.register;

import java.awt.*;
import javax.swing.*;

import java.io.*;

import master.*;

public class QuantumRegisterIO {
	
	public static final String registerSuffix = "qreg";
	
	public static QuantumRegister readRegister(String filename) throws QuantumRegisterException{
		try{
			FileInputStream myFIS = new FileInputStream(filename);
			ObjectInputStream myOIS = new ObjectInputStream(myFIS);
			try{
				Object myR = myOIS.readObject();
				
				if(myR instanceof QuantumRegister)
					return (QuantumRegister) myR;
				else
					throw new QuantumRegisterException("Error Loading register: "+filename + ", object file not a register");
				}catch(ClassNotFoundException e){
					
				}
			myOIS.close();
			myFIS.close();
		}catch(IOException e){
			
		}
		throw new QuantumRegisterException("Error Loading register: "+filename);
	}
	public static void writeRegister(QuantumRegister reg, String filename) throws QuantumRegisterException{
		try{
			FileOutputStream myFOS = new FileOutputStream(filename);
			ObjectOutputStream myOOS = new ObjectOutputStream(myFOS);
			myOOS.writeObject(reg);
			myOOS.close();
			myFOS.close();
		}catch(IOException e){
			throw new QuantumRegisterException("Error writing register");
		}
	}
	public static QuantumRegister loadDialog() throws QuantumRegisterException{
		FileDialog myDialog = new FileDialog(new JFrame());
		myDialog.setMode(FileDialog.LOAD);
		myDialog.setFilenameFilter(new QRegFilenameFilter());
		
		myDialog.setVisible(true);
		String dir = myDialog.getDirectory();
		String filename = myDialog.getFile();
		if(filename == null) throw new QuantumRegisterException("no register selected");
		
		System.out.println("("+dir+filename+")");
		try{
			return readRegister(dir+filename);
		}catch(QuantumRegisterException e){
			JOptionPane.showMessageDialog(null, "Error, register not loaded");
			throw e;
		}
		
	}
	public static void saveDialog(QuantumRegister r) throws QuantumRegisterException{
		FileDialog myDialog = new FileDialog(new JFrame());
		myDialog.setMode(FileDialog.SAVE);
		myDialog.setFilenameFilter(new QRegFilenameFilter());
		myDialog.setVisible(true);
		String dir = myDialog.getDirectory();
		String filename = myDialog.getFile();
		if(filename == null) throw new QuantumRegisterException("no register selected");
		try{
			writeRegister(r,dir+filename);
		}catch(QuantumRegisterException e){
			JOptionPane.showMessageDialog(null, "Error, register not saved");
			throw e;
		}
	}
}
